package com.fancon.rage.comic.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.fancon.rage.comic.domain.Image;
import com.fancon.rage.comic.domain.ImageRepository;

@Controller
@RequestMapping(value = "/images")
public class ImagesController {
	@Autowired
	private ImageRepository imageRepository;

	// @Autowired
	// private ImageDao dao;

	@RequestMapping(value = "manage", method = RequestMethod.GET)
	public String manage(Model model) throws IOException {
		Collection<Image> greetings = imageRepository.findAll();
		model.addAttribute("greeting", greetings);

		return "manage";
	}

	@RequestMapping(value = "view", method = RequestMethod.GET)
	public void view(HttpServletRequest req, HttpServletResponse resp,
			HttpSession session) throws IOException {
		long id = Long.parseLong(req.getParameter("id").replace("_", "")); // WTF?
		try {
			showRecord(id, req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public String upload(HttpServletRequest req, HttpServletResponse resp,
			HttpSession session) throws IOException {
		try {
			return handleSubmit(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "redirect:/greetings/images/manage";
	}

	protected void showRecord(long id, HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		Image photo = imageRepository.get(id);
		resp.setContentType(photo.getContentType());
		resp.getOutputStream().write(photo.getPhotoData());
		resp.flushBuffer();
	}

	protected String handleSubmit(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		ServletFileUpload upload = new ServletFileUpload();

		try {
			FileItemIterator it = upload.getItemIterator(req);

			Image photo = new Image();

			while (it.hasNext()) {
				FileItemStream item = it.next();
				String fieldName = item.getFieldName();
				InputStream fieldValue = item.openStream();

				if ("title".equals(fieldName)) {
					photo.setTitle(Streams.asString(fieldValue));
					continue;
				}

				if ("caption".equals(fieldName)) {
					photo.setCaption(Streams.asString(fieldValue));
					continue;
				}

				if ("file".equals(fieldName)) {
					photo.setContentType(item.getContentType());
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					Streams.copy(fieldValue, out, true);
					photo.setPhotoData(out.toByteArray());
					continue;
				}
			}

			imageRepository.save(photo);
			return "redirect:/greetings/images/view?id="+photo.getId();
			//resp.sendRedirect("datastore?action=display&id=" + photo.getId());
		} catch (FileUploadException e) {
			throw new ServletException(e);
		}
	}
}
